<?php
namespace control;

class customerStorageClass extends adIndexClass
{
    private const page = 'customerStorage'; # 权限
    private const table = 'customer_storage'; # 数据表
    private const title = '客户寄存';
    private const stateOption = ['草稿', '在库', '已发货'];
    private const tableKehu        = 'kehu';

    /**
     * 字段初始化
     */
    public function fieldInit(): array
    {
        $tr = [
            'orderNo' => [
                'name'  => '安检码',
                'width' => 200,
                'sort' => 1,
            ],
            'model'  => [
                'name'  => '规格型号',
                'width' => 200,
            ],
            'weight'         => [
                'name'  => '寄存重量',
                'width' => 200,
            ],
            'clientName'          => [
                'name'  => '寄存客户',
                'width' => 200,
            ],
            'state'          => [
                'name'  => '状态',
                'width' => 150,
            ],

        ];
        return $tr;
    }

    /*列表页-查询条件*/
    public function homeOptions($isAsync = true)
    {
        //生成查询表单
        $html = $this->tableShow([
            [
                [
                    '安检码'   => text(array("name" => "orderNo")),
                    '规格型号'  => text(array("name" => "model")),
                    '寄存客户' => clientClass::kehuSelect(array('name'=>'khid', "title" => '')),
                ],
                [
                    '状态' => select(["name" => "state", 'option' => self::stateOption]),
                ]
            ]
        ],1);
        //返回
        if (!$isAsync) {
            return $html;
        } else {
            return json_encode(['html' => $html], 320);
        }
    }

    /*销售合同入口页*/
    public function home()
    {
        $html = $this->homeOptions(false);
        //控件
        $button = "";
        $url = root . "control/adIndex.html?cla=" . self::page;
        if ($this->power(self::page, "edit")) {
            $button .= "<span onclick=\"layer('" . self::page . "','edit',{})\" class='spanButton'>新增</span>\n";
        }
        if ($this->power(self::page, "del")) {
            $button .= "<span class='spanButton' onclick=\"layer('{$this->get('cla')}', 'operate', {'act': 'del'})\">删除</span>\n";
        }
        //导入
        if ($this->power(self::page, 'import')) {
            $button .="<span class='spanButton' onclick=\"layer('importTemplate','importFrame',{cla:'".self::page."'})\">导入</span>";
        }
        if ($this->power(self::page, "export")) {
            $button .="<span class='spanButton' onclick=\"layer('importTemplate','exportFrame',{cla:'".self::page."'})\">导出</span>";
        }
        if ($this->power(self::page, "warehousing")) {
            $button .= "<span class='spanButton' onclick=\"layer('{$this->get('cla')}', 'operate', {'act': 'warehousing'})\">入库</span>\n";
        }
        if ($this->power(self::page, "delivery")) {
            $button .= "<span class='spanButton' onclick=\"layer('{$this->get('cla')}', 'operate', {'act': 'delivery'})\">发货</span>\n";
        }
        //返回
        return $this->homeFun($this->search($html, layout: 'pop', toolButton: $button));
    }

    /*销售合同列表*/
    public function homeSearch()
    {
        //查询结果
        $where = ' 1=1 ';
        $equal = [
            'orderNo' => $this->post('orderNo'),
            'model' => $this->post('model'),
            'khid' => $this->post('khid'),
            'state' => $this->post('state'),
            'coid'=>self::$coid
        ];
        //生成查询语句
        $where .= search([
            "=" => $equal,
        ]);

        //排序
        $orderBy = $this->listSort(array(
            "search"  => $this->post('list_sort_key') ?: 'time',
            "sort" => $this->post('list_sort') ?: "desc",
            "array"   => array(),
        ));
        $page = $this->page(["table" => self::table, "where" => $where, "order" => $orderBy['orderBy']]);
        $_SESSION[self::page]['where'] = $where;
        //获取自定义字段参数
        $installSearch = $this->installSearch();
        $body          = [];
        //表格控件区
        $liButton = array(
            $this->checkAll("listForm", "listId")
        );
        $url = root . "control/adIndex.html?cla=" . self::page;
        //获取记录
        foreach ($page['array'] as $array) {
            //列表控件
            $dominate = [
                "box" => ["name" => "listId", "value" => $array['id']],
            ];
            $liButton[] = $this->dominate($dominate);
            //本行初始化
            $row = [];
            foreach ($installSearch['key'] as $key) {
                switch ($key) {

                    default:
                        $row[] = isset($array[$key]) && $array[$key] ? $array[$key] : '';
                }
            }
            $body[] = $row;
        }
        //生成页面
        $li = $this->li(array(
            "body" => $body,
            "install" => $installSearch,
            "button" => array("html" => $liButton),
            "orderBySign" => $orderBy,
            "page" => $page['para'],
        ));
        //返回
        $json['html'] = "<form name='listForm'>" . $li . "</form>" . $page['button'] . $this->js(). clear;
        return json_encode($json, 320);
    }


    public function js()
    {
        return <<<eof
<script>
function addRow(){
    $.post(root+'control/adIndex.html?cla={$this->get('cla')}&fun=addMxEdit',$("form[name='mxForm']").serialize(),function(res) {
       $('#customerStorageAddMx').hide()
       $("#materialName").html(res.data.name);
       $("[name='materialId']").val(res.data.materialId);
       $("[name='model']").val(res.data.model);
    },'json');
}
</script>
eof;
    }

    /**
     * 编辑页
     *
     * @return string
     */
    public function edit(): string
    {
        $info = query(self::table, " id = '" . $this->post('id') . "' ");
        $name = materialClass::getName($info['materialId']);
        $html = $this->layerEdit(array(
            "table" => array(
                array(
                    must . "物料：" => "<span id='materialName' class='exceed-ellipsis' style='max-width: 90%;'>$name</span>&nbsp;<span class='del-row-button' onclick=\"layer('{$this->get('cla')}','addMx',{})\">选择</span>" . hidden(array('name' => 'materialId', 'value' => $info['materialId'])) . hidden(array('name' => 'model', 'value' => $info['model'])),
                ),
                array(
                    must . "安检码：" => text(array('name' => 'orderNo', 'value' => $info['orderNo'])),
                ),
                array(
                    must . "寄存重量：" => text(array('name' => 'weight', 'value' => $info['weight'])),
                ),
                array(
                    must . "寄存客户：" => clientProfileClass::kehuSelect(array('value' => $info['khid'])),
                ),
            ),
        ));
        return $this->layer(array("title" => "编辑", "height" => 350, "width" => 900, "html" => $html));
    }


    public function editEdit()
    {
        $id         = $this->post('id') ?: self::getId();
        $field      = [
            "materialId"   => $this->post('materialId'),
            "khid"            => $this->post('khid'),
            "orderNo"         => $this->post('orderNo'),
            "weight"          => $this->post('weight'),
            "state"          => $this->post('state'),
            "model"          => $this->post('model'),
            "updateTime"     => date('Y-m-d H:i:s'),
        ];
        $annotation = [
            'khid'          => '客户',
            'materialId' => '物料',
        ];
        $rules      = [
            'khid'          => 'required',
            'materialId' => 'required',
        ];
        // 校验是否符合规则
        $vt     = new \verify();
        $result = $vt->setAliases($annotation)->validate($field, $rules)->isOk();
        if ($result === false) {
            $json['warn'] = $vt->getErrs()[0];  // 多个规则提示最前面一条
            goto resp;
        }
        $where = " id = '$id' ";
        $info  = query(self::table, $where);
        //判断
        if (!$this->power(self::page, "edit")) {
            $json['warn'] = "你没有编辑" . self::title . "的权限";
        } elseif (static::total(array(
                'table' => self::table,
                'where' => "materialId = '$field[materialId]' and khid = '$field[khid]' and coid = '" . self::$coid . "'  and id !='$id'"
            )) > 0) {
            $json['warn'] = '此客户已存在此物料的价格本';
        } else {
            $kehu     = query(self::tableKehu, " khid = '$field[khid]' ");
            if (!$info['id']) {
                $field        = array_merge($field, [
                    'id'   => $id,
                    'coid' => self::$coid,
                    'stid' => $this->control['stid'],
                    'state' => '草稿',
                    'clientName' => $kehu['companyName'],
                ]);
                $json['warn'] = static::insert(["table" => self::table, "field" => $field]);
            } else {
                $json['warn'] = static::update([
                    "table" => self::table,
                    "where" => $where,
                    "field" => $field,
                    'state' => '草稿',
                    'clientName' => $kehu['companyName'],
                ]);
            }
            if (in_array($json['warn'], ["新增成功", "更新成功"])) {
                //添加日志
                $type = mb_substr($json['warn'], 0, 2, 'utf-8');
                $text = $this->control['name'] . $type . "了" . self::title . " id：【" . $id . '】';
                $this->logText(["type" => self::page, "text" => $text]);
                //返回
                $_SESSION['warn'] = $json['warn'];
                $json['warn']     = 2;
            }
        }

        resp:
        return json_encode($json, 320);
    }

    /**
     * @return bool|string
     */
    public function addMx()
    {
        $html   =
            materialClass::typeSelect(name: 'type').
            text(array("name" => "code", "title" => "产品编码")) .
            text(array("name" => "materialName", "title" => "产品名称")) .
            text(array("name" => "model", "title" => "规格型号"));
        $button = "<input style='margin-left: 5px' onclick=\"addRow()\" type='button' class='searchSub' value='提交'>";
        $html   = $this->search($html);
        return $this->layer(array("title" => "添加", "height" => 600, "width" => 1000, "zindex" => 3, "html" => $html, "button" => $button));
    }

    /**
     *添加产品
     */
    public function addMxSearch()
    {
        $like        = [
            'a.name'          => $this->post('materialName'),
            'code'            => $this->post('code'),
            'model'           => $this->post('model'),
            'a.supplyControl' => '允许销售',
            'a.typePath' => $this->post('type'),
        ];
        $equal       = [
            'a.coid'   => self::$coid,
            'a.state'  => '启用',
        ];
        $where       = search(["like" => $like, "=" => $equal]);
        $page        = $this->page([
            "table"   => "material as a",
            "field"   => "a.*",
            "where"   => $where,
            'pageNum' => 50,
            "order"   => "a.`time` ASC",
        ]);
        $materialObj = new materialClass();
        //获取表头
        $tr[]     = ['', '分类', '产品编码', '产品名称', '规格型号'];
        //获取记录
        foreach ($page['array'] as $array) {
            $checkBox = "<input name='mxId' value='$array[id]' type='radio'>";
            $tr[]     = array(
                $checkBox,
                $materialObj::getTypePath($array['typeId']),
                $array['code'],
                $array['name'],
                $array['model']
            );
        }
        $json['html'] = $page['hint'] . "<form name='mxForm'>" . $this->tableMany(array("tr" => $tr)) . "</form>" . $page['button'];
        return json_encode($json, 320);
    }

    /**
     * 编辑
     *
     * @return bool|string
     */
    public function addMxEdit()
    {
        $mxId = $this->post('mxId');
        if (!$this->power(self::page, 'edit')) {
            $json['warn'] = '你还没有编辑权限';
        } elseif (empty($mxId)) {
            $json['warn'] = '请选择产品';
        } else {
            $material = query('material',"id = '$mxId'");
            $json['data'] = [
                'materialId' => $material['id'],
                'model' => $material['model'],
                'name'          => materialClass::getName($material['id']),
            ];
            $json['warn'] = 2;
        }
        return json_encode($json, 320);
    }

    // 操作中转
    public function operate(): bool|string
    {
        $act  = $this->post('act') ?? '';
        $pwd  = false; // 需要密码
        $form = $word = $power = '';
        switch ($act) {
            case 'warehousing':
                $act      = 'warehousing';
                $msg      = '入库';
                $title    = '是否已确认此入库，确认后将不可修改？';
                $function = 'warehousing';
                $form     = self::page . 'OperateForm, listForm';
                $power    = '';
                $word = true;
                break;
            case 'delivery':
                $act      = 'delivery';
                $msg      = '发货';
                $title    = '是否已确认此发货，确认后将不可修改？';
                $function = 'delivery';
                $form     = self::page . 'OperateForm, listForm';
                $power    = '';
                $word = true;
                break;
            default:
                $act      = 'del';
                $msg      = '删除';
                $title    = '是否删除所选信息，删除后不可找回？';
                $function = 'delete';
                $form     = self::page . 'OperateForm, listForm';
                $power    = '';
                $word = true;
                break;
        }
        if (!$this->power(self::page, $act)) {
            $_SESSION['warn'] = '你还没有' . $msg . '的权限';
            $json             = [
                'warn' => 2,
                'href' => root . 'control/adIndex.html?cla=' . $this->get('cla') . '&fun=home',
            ];
        } else {
            return $this->confirm([
                'title'    => $title,
                'function' => $function,
                'form'     => $form,
                'power'    => $power,
                'pwd'      => $pwd,
                'word'     => $word,
            ]);
        }

        resp:
        return json_encode($json, 320);
    }

    /**
     * 删除
     *
     * @return bool|string
     */
    public function delete(): bool|string
    {
        $array = $this->post('listId') ?? $this->post('id');
        if (!$this->power(self::page, "del")) {
            $json['warn'] = "你没有删除的权限";
        } elseif (empty($array)) {
            $json['warn'] = "你一个数据都没有选择呢";
        } else {
            $text  = "";
            $x     = 0;
            $array = is_array($array) ? $array : [$array];
            foreach ($array as $id) {
                $info = query(self::table, " id = '$id' ");
                //最后删除基本参数
                delete(array("table" => self::table, "where" => " id = '$id' "));
                //返回
                $warn = "删除成功";
                $x++;
                $text .= self::title . "ID【" . $info['id'] . "】" . $warn . "。<br>";
            }
            //添加日志
            $text = $this->control['name'] . "删除了" . self::title . "，结果如下：<br>" . $text;
            $this->logText(array("type" => self::page, "text" => $text));
            $_SESSION['warn'] = "删除了" . $x . "个" . self::title . "，详情见系统日志。";
            $json['warn']     = 2;
            $json['href']     = root . "control/adIndex.html?cla=" . $this->get('cla') . "&fun=home";
        }
        return json_encode($json, 320);
    }

    /**
     * 入库
     * @return bool|string
     */
    public function warehousing(): bool|string
    {
        $array = $this->post('listId') ?? $this->post('id');
        if (!$this->power(self::page, "del")) {
            $json['warn'] = "你没有编辑的权限";
        } elseif (empty($array)) {
            $json['warn'] = "你一个数据都没有选择呢";
        } else {
            $text  = "";
            $x     = 0;
            $array = is_array($array) ? $array : [$array];
            foreach ($array as $id) {
                $info = query(self::table, " id = '$id' ");
                //最后删除基本参数
                update(array("table" => self::table, "where" => " id = '$id' ","field" => ['state'=>'在库'],));
                //返回
                $warn = "编辑成功";
                $x++;
                $text .= self::title . "ID【" . $info['id'] . "】" . $warn . "。<br>";
            }
            //生成ru库单
            $bool = $this->addInsertInventory($array);
            if ($bool !== true) {
                $json['warn'] = $bool;
                return json_encode($json, 320);
            }
            //添加日志
            $text = $this->control['name'] . "编辑了" . self::title . "，结果如下：<br>" . $text;
            $this->logText(array("type" => self::page, "text" => $text));
            $_SESSION['warn'] = "编辑了" . $x . "个" . self::title . "，详情见系统日志。";
            $json['warn']     = 2;
            $json['href']     = root . "control/adIndex.html?cla=" . $this->get('cla') . "&fun=home";
        }
        return json_encode($json, 320);
    }
    /**
     * 发货
     * @return bool|string
     */
    public function delivery(): bool|string
    {
        $array = $this->post('listId') ?? $this->post('id');
        if (!$this->power(self::page, "del")) {
            $json['warn'] = "你没有编辑的权限";
        } elseif (empty($array)) {
            $json['warn'] = "你一个数据都没有选择呢";
        } else {
            $text  = "";
            $x     = 0;
            $array = is_array($array) ? $array : [$array];
            foreach ($array as $id) {
                $info = query(self::table, " id = '$id' ");
                //最后删除基本参数
                update(array("table" => self::table, "where" => " id = '$id' ","field" => ['state'=>'待出库'],));
                //返回
                $warn = "编辑成功";
                $x++;
                $text .= self::title . "ID【" . $info['id'] . "】" . $warn . "。<br>";
            }
            //生成出库单
            $bool = $this->insertInventory($array);
            if ($bool !== true) {
                $json['warn'] = $bool;
                return json_encode($json, 320);
            }
            //添加日志
            $text = $this->control['name'] . "编辑了" . self::title . "，结果如下：<br>" . $text;
            $this->logText(array("type" => self::page, "text" => $text));
            $_SESSION['warn'] = "编辑了" . $x . "个" . self::title . "，详情见系统日志。";
            $json['warn']     = 2;
            $json['href']     = root . "control/adIndex.html?cla=" . $this->get('cla') . "&fun=home";
        }
        return json_encode($json, 320);
    }

    /**
     * 生成出库单
     *
     */
    private function insertInventory($info): bool|string
    {
        $quality  = [];//质检分组
        $re_array = [];//根据客户重新分组
        $result   = find(array('table' => self::table, 'where' => "id in '".implode($info,"','")."' order by list asc"));
        foreach ($result['array'] as $array) {
            $material = query('material', "id = '$array[materialId]'", "OQC");
            if ($material['OQC']) {
                //质检
                $quality[$array['materialId']][$array['id']] = ['num' => $array['num']];
            }
            $re_array[$array['khid']][] = $array['id'];
        }
        $state                = '待出库';
        $confirmTime          = null;
        $index = 1;
        foreach ($re_array as $khid => $array) {
            $info = query(self::table, " id = '$array[id]' ");
            $kehu                 = query('kehu', "khid = '$info[khid]'");
            $material = query('material', "id = '$array[materialId]'");
            $id               = self::getId();
            $field            = [
                'id'               => $id,
                'type'             => '其他出库',
                'coid'             => self::$coid,
                'sourceTable'      => self::table,
                'sourceId'         => $info['id'],
                'warehouseId'      => '',
                'targetId'         => $khid,
                'classify'         => 0,
                'confirmTime'      => $confirmTime,
                'state'            => $state,
                'workFlow'         => !empty($quality) ? '待质检' : '已质检',
                'stid'             => self::$stid,
                'orderDate'        => $this->date,
                'sourceDate'       => $info['sourceDate'],
                'sourceNo'         => $info['orderNo'],
                'sourceTargetName' => $kehu['companyName'],
            ];
            $userNo           = codeTemplateClass::generateCode('outStock', [
                'prefix' => 'KCCK' . date('Ymd'),
                'table'  => 'inventory',
                'field'  => 'orderNo',
                'where'  => " and coid = '" . self::$coid . "'",
                'index'  => $index,
            ], $field);
            $field['orderNo'] = $userNo;
            $warn             = static::insert(array(
                'table' => 'inventory',
                'field' => $field,
            ));
            if ($warn != '新增成功') {
                return "新增出库单失败";
            }
            $num                         = $info['weight'];
            $warn = static::insert(array(
                'table' => 'inventory_detail',
                'field' => [
                    'id'          => self::getId(),
                    'coid'        => self::$coid,
                    'sourceTable' => self::table,
                    'sourceId'    => $info['id'],
                    'materialId'  => $info['materialId'],
                    'unit'        => $material['unit'],
                    'warehouseId' => '',
                    'positionId'  => '',
                    'orderId'     => $id,
                    'orderNum'    => $num,
                    'batch'       => '',
                    'num'         => $num,
                    'rate'        => 0 ,
                    'price'       => 0,
                    'money'       => 0,
                    'quality'       =>  0,
                    'pass_num'      =>  0,
                ],
            ));
            if ($warn != '新增成功') {
                return "新增出库单明细失败";
            }
        }
        return true;
    }

    /**
     * 生成入库单(需要生成质检单)
     */
    public function addInsertInventory($info, $isRoll = true): bool|string
    {
        $quality  = [];//质检分组
        $re_array = [];//根据客户重新分组
        $result   = find(array('table' => self::table, 'where' => "id in '".implode($info,"','")."' order by list asc"));
        foreach ($result['array'] as $array) {
            $material = query('material', "id = '$array[materialId]'", "OQC");
            if ($material['OQC']) {
                //质检
                $quality[$array['materialId']][$array['id']] = ['num' => $array['num']];
            }
            $re_array[$array['khid']][] = $array['id'];
        }
        $index = 1;
        //入库
        foreach ($re_array as $khid => $array) {
            $info = query(self::table, " id = '$array[id]' ");
            $kehu                 = query('kehu', "khid = '$info[khid]'");
            $material = query('material', "id = '$array[materialId]'");
            $id               = self::getId();
            $field = [
                'id' => $id,
                'type' => '其他入库',
                'coid' => self::$coid,
                'sourceTable' => self::table,
                'sourceId' => $info['id'],
                'warehouseId' => '',
                'targetId' => $kehu['khid'],
                'classify' => 1,
                'state' => '待入库',
                'workFlow' => !empty($quality) ? '待质检' : '已质检',
                'stid' => self::$stid,
                'orderDate' => $this->date,
                'sourceDate'       => $info['sourceDate'],
                'sourceNo'         => $info['orderNo'],
                'sourceTargetName' => $kehu['companyName'],
            ];
            $userNo = codeTemplateClass::generateCode('inStock', [
                'prefix' => 'KCRK' . date('Ymd'),
                'table' => 'inventory',
                'field' => 'orderNo',
                'where' => " and coid = '" . self::$coid . "'",
                'index' => $index
            ], $field);
            $index = $isRoll ? $index + 1 : $index;
            $field['orderNo'] = $userNo;
            $warn = static::insert(array(
                'table' => 'inventory',
                'field' => $field
            ));
            if ($warn != '新增成功') {
                return "新增入库单失败";
            }
            $warn = static::insert(array(
                'table' => 'inventory_detail',
                'field' => [
                    'id' => self::getId(),
                    'coid' => self::$coid,
                    'sourceTable' => self::table,
                    'sourceId'    => $info['id'],
                    'materialId' => $info['materialId'],
                    'warehouseId' => '',
                    'unit' => $material['unit'],
                    'orderId' => $info['id'],
                    'orderNum' => $info['weight'],
                    'price' => 0,
                    'batch' => '',
                    'quality'       => 0,
                    'pass_num'      =>0,
                ]
            ));
            if ($warn != '新增成功') {
                return "新增入库单明细失败";
            }
        }
        return true;
    }

}